﻿using Ldt.AnalysisRuleInfoUnit.Core.Database;
using LdtJudge.DatabaseHandle.Standard;
using LdtJudge.DataEngine.CallInterface.CommHelp;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Text.RegularExpressions;

namespace LdtJudge.DataEngine.Common.CommHelp
{
    /// <summary>
    /// 案由数据操作实体
    /// </summary>
    public class GetSysCaseCause
    {
        private IFreeSql freeSql = FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
        private Data.SqlSysCommon _sqlSyscom;

        #region 案由类相关操作

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connectionstring"></param>

        public GetSysCaseCause()
        {
            _sqlSyscom = new Data.SqlSysCommon("Ldt_JudgeDocSystem");
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CaseCauseModel GetModelByCauseName(string ccName, string caseType)
        {
            string caseTypee = _sqlSyscom.GetCaseTypeID(caseType);
            CaseCauseModel model = null;
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => (a.CC_Name == ccName || a.CC_ID == ccName) && a.CC_NodeType == 2).ToList();
            if (!string.IsNullOrEmpty(caseTypee))
            {
                sYS_CaseCausesList = sYS_CaseCausesList.Where(a => a.AllParentId.IndexOf(caseTypee) > -1).ToList();
            }
            if (sYS_CaseCausesList.Count > 0)
            {
                SYS_CaseCause query = GetCaseCause(sYS_CaseCausesList);
                model = ReaderBind(query);
            }
            return model;
        }

        /// <summary>
        /// 通过案由名称 案由ID和案件类型编号查询案由数据
        /// </summary>
        public CaseCauseModel GetModelByCauseNamexzzf(string ccName, string caseType)
        {
            string caseTypee = _sqlSyscom.GetCaseTypeID(caseType);
            CaseCauseModel model = null;
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => (a.CC_Name == ccName || a.CC_ID == ccName) && a.CC_NodeType == 2).ToList();
            if (!string.IsNullOrEmpty(caseTypee))
            {
                sYS_CaseCausesList = sYS_CaseCausesList.Where(a => a.AllParentId.IndexOf(caseTypee) > -1).ToList();
            }
            if (sYS_CaseCausesList.Count > 0)
            {
                model = ReaderBind(sYS_CaseCausesList[0]);

            }
            return model;
        }

        /// <summary>
        /// 查询法规关联信息数据
        /// </summary>
        public List<SYS_QuoteLawRel> GetSYS_QuoteLawRelByOLR_CaseCauseIDAndOLR_SituationID(string OLR_CaseCauseID, string OLR_SituationID)
        {
            List<SYS_QuoteLawRel> sYS_QuoteLawRelList = freeSql.Select<SYS_QuoteLawRel>().Where(a => a.OLR_CaseCauseID == OLR_CaseCauseID && a.OLR_SituationID == OLR_SituationID).ToList();
            return sYS_QuoteLawRelList;
        }

        /// <summary>
        /// 得到一个案由实体
        /// </summary>
        public CaseCauseModel GetModel(string CC_ID)
        {
            CaseCauseModel model = null;
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.CC_ID == CC_ID).ToList().ToList();
            if (sYS_CaseCausesList.Count > 0)
            {
                model = ReaderBind(sYS_CaseCausesList[0]);
            }

            return model;
        }

        /// <summary>
        /// 根据上级ID返回对象实体
        /// </summary>
        /// <param name="ParentID"></param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetCaseCauseByParentid(string ParentID)
        {
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.CC_ParentID == ParentID && a.CC_NodeType != 4).ToList().ToList();
            return sYS_CaseCausesList;
        }

        /// <summary>
        /// 根据上级ID返回对象实体
        /// </summary>
        /// <param name="ParentID"></param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetCaseCauseByParentid_new(string ParentID)
        {
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.CC_ParentID == ParentID && a.CC_Name == "案由要素").ToList().ToList();
            return sYS_CaseCausesList;
        }

        /// <summary>
        /// 根据上级ID返回对象实体
        /// </summary>
        /// <param name="ParentID"></param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetCaseCauseByAllParentId(string AllParentId)
        {
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.AllParentId.IndexOf(AllParentId) > -1 && (a.CC_NodeType == 15 || a.CC_NodeType == 16)).ToList().ToList();
            return sYS_CaseCausesList;
        }

        /// <summary>
        /// 通过AllParentId查询类型为17的案由
        /// </summary>
        /// <param name="AllParentId"></param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetCaseCauseByAllParentIds(string AllParentId)
        {
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.AllParentId.IndexOf(AllParentId) > -1 && a.CC_NodeType == 17).ToList().ToList();
            return sYS_CaseCausesList;
        }

        /// <summary>
        ///根据caseID获取字典实体
        /// </summary>
        /// <param name="causeID"></param>
        /// <returns></returns>
        public List<SYS_ArgumentType> GetArgumentTypeByAt_CauseID(string causeID)
        {
            List<SYS_ArgumentType> sYS_CaseCausesList = freeSql.Select<SYS_ArgumentType>().Where(a => a.AT_CauseID == causeID).ToList();
            return sYS_CaseCausesList;
        }

        /// <summary>
        /// 通过父级Id 地域Id查询类型为5或6的案由
        /// </summary>
        public List<SYS_CaseCause> GetCaseCauseMatchValueIDByCauseID(string causeID)
        {
            Expression<Func<SYS_CaseCause, bool>> where = (x) => true;
            where = where.And(a => a.AllParentId.IndexOf(causeID) > -1 && (a.CC_NodeType == 5 || a.CC_NodeType == 6) && (a.IsML != 1 || a.IsML == null));
            List<SYS_CaseCause> sYS_CaseCauses = freeSql.Select<SYS_CaseCause>().Where(where).ToList();
            return sYS_CaseCauses;
        }

        /// <summary>
        /// 查询得到需要匹配的情形
        /// </summary>
        /// <returns></returns>
        public List<SYS_CaseCause> GetCaseCauseMatchValueID(string isml)
        {
            Expression<Func<SYS_CaseCause, bool>> where = (x) => true;
            if (isml == "1")
            {
                where = where.And(a => ((a.AllParentId + ",").IndexOf("1000,1111111,") > -1 || (a.AllParentId + ",").IndexOf("1000,2222222,") > -1) && (a.IsML == 1));
            }
            else
            {
                where = where.And(a => ((a.AllParentId + ",").IndexOf("1000,1111111,") > -1 || (a.AllParentId + ",").IndexOf("1000,2222222,") > -1));
            }

            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(where).ToList();
            string sql = freeSql.Select<SYS_CaseCause>().Where(where).ToSql();
            return sYS_CaseCauseList;
        }

        /// <summary>
        /// 查询违法行为案由数据
        /// 行政执法==通过领域ID(cc_id)查找CC_NodeType=28的数据
        /// </summary>
        public List<SYS_CaseCause> GetCaseCausesValueIDByAfford(string causeID, string isml)
        {
            List<SYS_CaseCause> sYS_CaseCauseList = new List<SYS_CaseCause>();
            if (isml == "1")
            {
                sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(a => a.CC_ParentID == causeID && a.CC_Name == "违法行为" && (a.IsML == null || a.IsML == 0)).
                 ToList();
            }
            else
            {
                sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(a => a.CC_ParentID == causeID && a.CC_Name == "违法行为").
                  ToList();
            }


            return sYS_CaseCauseList;
        }

        /// <summary>
        /// 通过父级ID查询相同类型的案由数据
        /// </summary>
        public List<SYS_CaseCause> GetCaseCausesValueAfford(string causeID, int nodetype)
        {
            Expression<Func<SYS_CaseCause, bool>> where = (e) => true;
            where = where.And(x => x.AllParentId.IndexOf(causeID) > -1 && x.CC_NodeType == nodetype);
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(where).ToList();
            return sYS_CaseCauseList;
        }

        /// <summary>
        /// TODO:ZSW District
        /// 行政执法==>通过领域Id和地域查询违法行为数据
        /// </summary>
        /// <param name="causeID">领域ID</param>
        /// <param name="nodetype">案由节点类型</param>
        /// <param name="district">地域</param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetOffenceCauses(string causeID, int nodetype, string district)
        {
            List<SYS_CaseCause> result = freeSql.Select<SYS_CaseCause, Xzzf_DisWfRel>()
                          .InnerJoin((a, b) => a.CC_ID == b.WF_ID)
                          .Where((a, b) => a.AllParentId.IndexOf(causeID) > -1 && a.CC_NodeType == nodetype)
                          .Where((a, b) => b.CC_District == district)
                          .ToList((a, b) => a).Distinct().ToList();
            return result;
        }


        /// <summary>
        /// TODO:ZSW District
        /// 行政执法==>通过违法行为ID和地域查询裁量情节数据
        /// </summary>
        /// <param name="causeID">违法行为ID</param>
        /// <param name="parentId">父级ID</param>
        /// <param name="nodetype">案由节点类型</param>
        /// <param name="district">地域</param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetDiscretionaryPlotCauses(string causeID, string parentId, int nodetype, string district)
        {
            List<SYS_CaseCause> result = freeSql.Select<SYS_CaseCause, Xzzf_DisWfRel, Xzzf_WfClRel>()
                         .InnerJoin((a, b, c) => a.CC_ID == b.WF_ID)
                         .InnerJoin((a, b, c) => b.RC_ID == c.RC_ID)
                         .Where((a, b, c) => a.AllParentId.IndexOf(causeID) > -1 && a.CC_NodeType == nodetype)
                         .WhereIf(!string.IsNullOrWhiteSpace(parentId), (a, b, c) => a.CC_ParentID == parentId)
                         .Where((a, b, c) => b.CC_District == district)
                         .ToList((a, b, c) => a).Distinct().ToList();
            return result;
        }

        /// <summary>
        /// TODO:ZSW District
        /// 行政执法==>通过违法行为ID和地域查询裁量情节数据
        /// </summary>
        /// <param name="causeID">违法行为ID</param>
        /// <param name="nodetype">案由节点类型</param>
        /// <param name="district">地域</param>
        /// <returns></returns>
        public List<SYS_CaseCause> GetDiscretionaryPlotCauses(string causeID, List<int> nodetypes, string district)
        {
            List<SYS_CaseCause> result = freeSql.Select<SYS_CaseCause, Xzzf_DisWfRel, Xzzf_WfClRel>()
                         .InnerJoin((a, b, c) => a.CC_ID == b.WF_ID)
                         .InnerJoin((a, b, c) => b.RC_ID == c.RC_ID)
                         .Where((a, b, c) => a.AllParentId.Contains(causeID) && a.CC_NodeType.HasValue && nodetypes.Contains(a.CC_NodeType.Value))
                         .Where((a, b, c) => b.CC_District == district)
                         .ToList((a, b, c) => a).Distinct().ToList();
            var sql = freeSql.Select<SYS_CaseCause, Xzzf_DisWfRel, Xzzf_WfClRel>()
                         .InnerJoin((a, b, c) => a.CC_ID == b.WF_ID)
                         .InnerJoin((a, b, c) => b.RC_ID == c.RC_ID)
                         .Where((a, b, c) => a.AllParentId.Contains(causeID) && a.CC_NodeType.HasValue && nodetypes.Contains(a.CC_NodeType.Value))
                         .Where((a, b, c) => b.CC_District == district).ToSql();
            return result;
        }



        /// <summary>
        /// 通过父级ID和地域查询多种类型的案由数据
        /// </summary>
        public List<SYS_CaseCause> GetCaseCausesValueAfford(string causeID, int nodetype, int nodetypetow)
        {
            Expression<Func<SYS_CaseCause, bool>> where = (x) => true;
            where = where.And(a => a.AllParentId.IndexOf(causeID) > -1 && (a.CC_NodeType == nodetype || a.CC_NodeType == nodetypetow));
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(where).ToList();
            return sYS_CaseCauseList;
        }

        /// <summary>
        /// 根据ccID获取情形信息
        /// </summary>
        /// <param name="ccid"></param>
        /// <returns></returns>
        public SYS_CaseCause GetCauseModel(string ccid)
        {
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where
                   (a => a.CC_ID == ccid).ToList();
            if (sYS_CaseCauseList.Count > 0)
            {
                return sYS_CaseCauseList[0];
            }
            return null;
        }

        /// <summary>
        /// 查询相同类型的案由数据
        /// </summary>
        public SYS_CaseCause GetCauseModelNodeType(int type)
        {
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where
                   (a => a.CC_NodeType == type).ToList();
            if (sYS_CaseCauseList.Count > 0)
            {
                return sYS_CaseCauseList[0];
            }
            return null;
        }

        /// <summary>
        /// 通过案件类型编号查询案件类型与案由关系表数据
        /// </summary>
        /// <param name="caseType">案件类型编号</param>
        /// <returns></returns>
        public SYS_Casetype_CaseCauseRel Get_CaseCauseRel(string caseType)
        {
            List<SYS_CaseType> sYS_CaseTypes = freeSql.Select<SYS_CaseType>().Where(a => a.CT_Code == caseType).ToList();
            if (sYS_CaseTypes.Count > 0)
            {
                List<SYS_Casetype_CaseCauseRel> sYS_Casetype_CaseCauseRelList = freeSql.Select<SYS_Casetype_CaseCauseRel>().Where
                  (a => a.CaseTypeID == sYS_CaseTypes[0].CaseTypeID).ToList();
                if (sYS_Casetype_CaseCauseRelList.Count > 0)
                {
                    return sYS_Casetype_CaseCauseRelList[0];
                }
            }

            return null;
        }

        /// <summary>
        /// 寻找父级ID与类型相同的数据
        /// </summary>
        /// <param name="parentId">父级ID</param>
        /// <param name="type">案由类型</param>
        /// <returns></returns>
        public SYS_CaseCause GetCauseModel(string parentId, int type)
        {
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where
                  (a => a.CC_ParentID == parentId && a.CC_NodeType == type).ToList();
            if (sYS_CaseCauseList.Count > 0)
            {
                return sYS_CaseCauseList[0];
            }
            return null;


        }

        /// <summary>
        /// 查询罪名值
        /// </summary>
        public List<SYS_CaseCause> GetMatchValueIDByCauseID(string CauseID, string isml)
        {
            //SELECT * FROM dbo.SYS_CaseCause WHERE AllParentId LIKE '%," + CauseID + ",%'  AND cc_nodetype = 4   ORDER BY CC_GlobalOrder
            Expression<Func<SYS_CaseCause, bool>> where = (x) => true;
            if (isml == "1")
            {
                where = where.And(a => a.AllParentId.Contains(CauseID) && a.CC_NodeType == 4 && a.IsML == 1);
            }
            else
            {
                where = where.And(a => a.AllParentId.Contains(CauseID) && a.CC_NodeType == 4);
            }

            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(where).ToList();
            return sYS_CaseCauseList;
        }

        /// <summary>
        /// 把查询到的数据Table转为强类型MSYS_CaseCause
        /// </summary>
        /// <param name="CauseID">案由ID</param>
        /// <returns></returns>
        public IList<CaseCauseModel> GetList_FactElement(string CauseID)
        {
            return GetTable_FactElement(CauseID);
        }

        /// <summary>
        /// 得到案由相关的事实要素XML配置
        /// </summary>
        /// <param name="CauseID"></param>
        /// <returns></returns>
        public List<CaseCauseModel> GetTable_FactElement(string CauseID)
        {
            List<SYS_CaseCause> sYS_CaseCauseList = freeSql.Select<SYS_CaseCause>().Where(a => a.AllParentId.IndexOf(CauseID.ToString()) > -1 && (a.CC_NodeType == 11 || a.CC_NodeType == 12)).ToList();

            List<CaseCauseModel> caseCauseModelList = new List<CaseCauseModel>();
            foreach (SYS_CaseCause casecuse in sYS_CaseCauseList)
            {
                try
                {
                    caseCauseModelList.Add(CopySameFieldsObject<CaseCauseModel>(casecuse));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return caseCauseModelList;
        }

        /// <summary>
        /// 转换两个不同类型但是成员相同的对象
        /// </summary>
        /// <typeparam name="T">目标对象</typeparam>
        /// <param name="source">待转换对象</param>
        /// <returns></returns>
        public static T CopySameFieldsObject<T>(Object source)
        {
            return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));
        }

        /// <summary>
        /// 根据案件类型获取可分析文书
        /// </summary>
        public List<SYS_CaseCause> GetLoadCauseCurrentPersonFact(string casetype, string causeid)
        {
            string strsql = $@"SELECT
                                                    scc.CC_ID,
                                                    scc.CC_Name,
                                                    scc.CC_ParentID,
                                                    scc.CC_NodeType,
                                                    scc.AllParentId,
                                                    scc.AllParentName,
                                                    scc.XmlPath,
                                                    esc.CC_RegexInfoCode AS CC_RegexInfoCodeTemp
                                                        FROM
                                                    dbo.SYS_CaseCause scc
                                                    RIGHT JOIN dbo.SYS_Express_Source esc ON esc.CC_ID = scc.CC_ID
                                                    WHERE
                                                    esc.ES_Purpose = 'AM1902281150330042' and lower(source_id)='" + casetype.ToLower() + "' and scc.AllParentId like '%" + causeid + "%'";
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause, SYS_Express_Source>().RightJoin((a, b) => a.CC_ID == b.CC_ID).Where((a, b) => b.ES_Purpose == "AM1902281150330042" && b.Source_ID.ToLower() == casetype.ToLower() && a.AllParentId.IndexOf(causeid) > -1).
                  ToList((a, b) => new SYS_CaseCause() { CC_ID = a.CC_ID, CC_Name = a.CC_Name, CC_ParentID = a.CC_ParentID, AllParentId = a.AllParentId, AllParentName = a.AllParentName, XmlPath = a.XmlPath, CC_RegexInfoCode = b.CC_RegexInfoCode });
            //string sqq= freeSql.Select<SYS_CaseCause, SYS_Express_Source>().RightJoin((a, b) => a.CC_ID == b.CC_ID).Where((a, b) => b.ES_Purpose == "AM1902281150330042" && b.Source_ID.ToLower() == casetype.ToLower() && a.AllParentId.IndexOf(causeid) > -1).ToSql();
            return sYS_CaseCausesList;

        }

        /// <summary>
        /// 通过父级ID和使用用途查询可分析文书
        /// </summary>
        public List<SYS_CaseCause> GetLoadCauseCurrentPersonFactlyu(string causeid)
        {
            string strsql = $@"SELECT
                                                    scc.CC_ID,
                                                    scc.CC_Name,
                                                    scc.CC_ParentID,
                                                    scc.CC_NodeType,
                                                    scc.AllParentId,
                                                    scc.AllParentName,
                                                    scc.XmlPath,
                                                    esc.CC_RegexInfoCode AS CC_RegexInfoCodeTemp
                                                        FROM
                                                    dbo.SYS_CaseCause scc
                                                    RIGHT JOIN dbo.SYS_Express_Source esc ON esc.CC_ID = scc.CC_ID
                                                    WHERE
                                                    esc.ES_Purpose = 'AM1902281150330042' and scc.AllParentId like '%,{causeid},%'";
            List<SYS_CaseCause> sYS_CaseCausesList = freeSql.Select<SYS_CaseCause, SYS_Express_Source>().RightJoin<SYS_CaseCause>((a, b) => a.CC_ID == b.CC_ID).Where((a, b) => b.ES_Purpose == "AM1902281150330042" && a.AllParentId.IndexOf(causeid) > -1).
              ToList((a, b) => new SYS_CaseCause() { CC_ID = a.CC_ID, CC_Name = a.CC_Name, CC_ParentID = a.CC_ParentID, AllParentId = a.AllParentId, AllParentName = a.AllParentName, XmlPath = a.XmlPath, CC_RegexInfoCode = b.CC_RegexInfoCode });
            return sYS_CaseCausesList;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CaseCauseModel DataRowToModel(DataRow row)
        {
            CaseCauseModel model = new CaseCauseModel();
            if (row != null)
            {
                if (row["CC_ID"] != null)
                {
                    model.CC_ID = row["CC_ID"].ToString();
                }
                if (row["CC_Name"] != null)
                {
                    model.CC_Name = row["CC_Name"].ToString();
                }
                if (row["CC_Code"] != null)
                {
                    model.CC_Code = row["CC_Code"].ToString();
                }
                if (row["CC_ParentID"] != null)
                {
                    model.CC_ParentID = row["CC_ParentID"].ToString();
                }
                if (row["CC_OfficialCode"] != null)
                {
                    model.CC_OfficialCode = row["CC_OfficialCode"].ToString();
                }
                if (row["CC_EqualCode"] != null)
                {
                    model.CC_EqualCode = row["CC_EqualCode"].ToString();
                }
                if (row["CC_SerialNumb"] != null && row["CC_SerialNumb"].ToString() != "")
                {
                    model.CC_SerialNumb = decimal.Parse(row["CC_SerialNumb"].ToString());
                }
                if (row["CC_Explain"] != null)
                {
                    model.CC_Explain = row["CC_Explain"].ToString();
                }
                if (row["isSave"] != null && row["isSave"].ToString() != "")
                {
                    model.isSave = int.Parse(row["isSave"].ToString());
                }
                if (row["CC_NodeType"] != null && row["CC_NodeType"].ToString() != "")
                {
                    model.CC_NodeType = int.Parse(row["CC_NodeType"].ToString());
                }
                if (row["isLeafNode"] != null && row["isLeafNode"].ToString() != "")
                {
                    model.isLeafNode = int.Parse(row["isLeafNode"].ToString());
                }
                if (row["AllParentId"] != null)
                {
                    model.AllParentId = row["AllParentId"].ToString();
                }
                if (row["HW_level"] != null && row["HW_level"].ToString() != "")
                {
                    model.HW_level = int.Parse(row["HW_level"].ToString());
                }
                if (row["CC_RegexInfoCode"] != null)
                {
                    model.CC_RegexInfoCode = row["CC_RegexInfoCode"].ToString();
                }
                if (row["AllParentName"] != null)
                {
                    model.AllParentName = row["AllParentName"].ToString();
                }
                if (row["CC_InferRuleTextByCode"] != null)
                {
                    model.CC_InferRuleTextByCode = row["CC_InferRuleTextByCode"].ToString();
                }
                if (row["ElementXML"] != null)
                {
                    model.ElementXML = row["ElementXML"].ToString();
                }
                if (row["OptimizeXML"] != null)
                {
                    model.ElementXML = row["OptimizeXML"].ToString();
                }
                if (row["ConfigXML"] != null)
                {
                    model.ElementXML = row["ConfigXML"].ToString();
                }

                if (row["CC_IsDefineExtract"] != null && row["CC_IsDefineExtract"].ToString() != "")
                {
                    model.CC_IsDefineExtract = int.Parse(row["CC_IsDefineExtract"].ToString());
                }

                if (row["CC_DefineExtractType"] != null)
                {
                    model.CC_DefineExtractType = row["CC_DefineExtractType"].ToString();
                }
                if (row["CC_GlobalOrder"] != null)
                {
                    model.CC_GlobalOrder = row["CC_GlobalOrder"].ToString();
                }
                if (row["XmlPath"] != null)
                {
                    model.XmlPath = row["XmlPath"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 通过案由名称获取案由数据
        /// </summary>
        public CaseCauseModel GetCauseByName(string ccName, DataContext dataContext = null)
        {
            CaseCauseModel caseCause = null;
            var queryList = freeSql.Select<SYS_CaseCause>()
                               .Where(x => (x.CC_Name == ccName || x.CC_ID == ccName) && (x.CC_NodeType == 12 || x.CC_NodeType == 2 || x.CC_NodeType == 21))
                               .ToList();
            if (queryList != null && queryList.Count > 0)
            {
                SYS_CaseCause query = GetCaseCause(queryList);
                if (query.CC_ID != null)
                {
                    caseCause = ReaderBind(query);
                }
                else
                {
                    //判断是否有拆分罪名，有的话就取父级
                    if (queryList.Any(x => x.CC_NodeType == 21))
                    {

                        dataContext?.InteractiveShow.LogShow("拆分罪名案由提取前结果：" + queryList.First(x => x.CC_NodeType == 21).CC_Name);
                        caseCause = ReaderBind(GetCaseCauseByParentID(queryList.First(x => x.CC_NodeType == 21).CC_ParentID));
                        dataContext?.InteractiveShow.LogShow("拆分罪名案由提取后结果：" + caseCause.CC_Name);
                    }
                    else
                    {
                        caseCause = ReaderBind(queryList[0]);
                    }
                }
            }

            return caseCause;
        }


        /// <summary>
        /// 存在相同名称的案由 取子级案由 比如：走私、贩卖、运输、制造毒品罪1289、1290
        /// </summary>
        /// <param name="queryList"></param>
        /// <returns></returns>
        private static SYS_CaseCause GetCaseCause(List<SYS_CaseCause> queryList)
        {
            SYS_CaseCause query = new SYS_CaseCause();
            if (queryList.Count == 1)
            {
                query = queryList[0];
            }
            else
            {
                queryList.ForEach(x =>
                {
                    string str = x.AllParentId + ",";
                    if (queryList.Any(x => x.AllParentId.Contains(str)))
                        query = queryList.FirstOrDefault(x => x.AllParentId.Contains(str));
                });
            }

            return query;
        }

        /// <summary>
        /// 根据父级Id返回是案由的节点
        /// </summary>
        /// <param name="parentID">父级Id</param>
        /// <returns>父级是案由的节点信息或者找不到父级为2的空节点</returns>
        private SYS_CaseCause GetCaseCauseByParentID(string parentID)
        {
            var res = freeSql.Select<SYS_CaseCause>().Where(x => x.CC_ID == parentID).First();
            if (res.CC_NodeType == 2)
            {
                return res;
            }
            else
            {
                return GetCaseCauseByParentID(res.CC_ParentID);
            }
        }

        /// <summary>
        /// 通过案由Id获取案由数据
        /// </summary>
        public CaseCauseModel GetCauseById(string ccid)
        {
            CaseCauseModel caseCause = null;
            var query = freeSql.Select<SYS_CaseCause>()
                             .Where(x => x.CC_ID == ccid)
                             .ToOne();
            if (query != null)
                caseCause = ReaderBind(query);
            return caseCause;
        }

        /// <summary>
        /// 加载案由实体
        /// </summary>
        public CaseCauseModel ReaderBind(SYS_CaseCause sYS_CaseCause)
        {
            CaseCauseModel model = new CaseCauseModel();
            object ojb;
            model.CC_ID = sYS_CaseCause.CC_ID;
            model.CC_Name = sYS_CaseCause.CC_Name;
            model.CC_Code = sYS_CaseCause.CC_Code;
            model.CC_ParentID = sYS_CaseCause.CC_ParentID;
            model.CC_OfficialCode = sYS_CaseCause.CC_OfficialCode;
            model.CC_EqualCode = sYS_CaseCause.CC_EqualCode;
            model.XmlPath = sYS_CaseCause.XmlPath;
            ojb = sYS_CaseCause.CC_SerialNumb;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_SerialNumb = (decimal)ojb;
            }
            model.CC_Explain = sYS_CaseCause.CC_Explain;
            ojb = sYS_CaseCause.isSave;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.isSave = (int)ojb;
            }
            ojb = sYS_CaseCause.CC_NodeType;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_NodeType = (int)ojb;
            }
            ojb = sYS_CaseCause.isLeafNode;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.isLeafNode = (int)ojb;
            }
            model.AllParentId = sYS_CaseCause.AllParentId;
            ojb = sYS_CaseCause.HW_level;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.HW_level = (int)ojb;
            }
            model.CC_RegexInfoCode = sYS_CaseCause.CC_RegexInfoCode;
            model.AllParentName = sYS_CaseCause.AllParentName;
            model.CC_InferRuleTextByCode = sYS_CaseCause.CC_InferRuleTextByCode;
            model.OptimizeXML = sYS_CaseCause.OptimizeXML;
            ojb = sYS_CaseCause.CC_IsDefineExtract;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_IsDefineExtract = (int)ojb;
            }
            model.CC_DefineExtractType = sYS_CaseCause.CC_DefineExtractType;
            model.CC_GlobalOrder = sYS_CaseCause.CC_GlobalOrder;

            ojb = sYS_CaseCause.CC_DevelopSchedule;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_DevelopSchedule = (int)ojb;
            }
            if (model.CC_NodeType == 2 || model.CC_NodeType == 28)
            {//如果是案由，则请求接口
                model.ElementXML = BllDataHandle.GetConfigContext(BllDataHandle.RemoteConfigSysType.SysJudge, "SYS_CaseCause\\ElementXML", model.CC_ID, "xml");
                model.ConfigXML = BllDataHandle.GetConfigContext(BllDataHandle.RemoteConfigSysType.SysJudge, "SYS_CaseCause\\ConfigXML", model.CC_ID, "xml");
            }
            else
            {
                model.ElementXML = "";
                model.ConfigXML = "";
            }

            ojb = sYS_CaseCause.CC_IsDefineExtract;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_IsDefineExtract = (int)ojb;
            }
            model.CC_DefineExtractType = sYS_CaseCause.CC_DefineExtractType;
            model.CC_GlobalOrder = sYS_CaseCause.CC_GlobalOrder;

            ojb = sYS_CaseCause.CC_DevelopSchedule;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_DevelopSchedule = (int)ojb;
            }
            //获取核心要素
            ojb = sYS_CaseCause.CC_IsBasicElements;
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CC_IsBasicElements = (int)ojb;
            }
            return model;

        }

        /// <summary>
        /// 如果案由获取为空，则进行根据内容进行重新获取案由
        /// </summary>
        /// <param name="textcentent">文本内容</param>
        /// <param name="caseType">案件类型</param>
        /// <returns></returns>
        public string GetCauseID(string textcentent, string caseType)
        {
            Dictionary<string, string> causeList = new Dictionary<string, string>();
            string sys_cause = string.Empty;
            string code = _sqlSyscom.GetCaseTypeID(caseType);
            List<SYS_CaseCause> sys_caseCausesList = freeSql.Select<SYS_CaseCause>().Where(a => a.AllParentId.IndexOf(code) > -1 && a.CC_NodeType == 2).ToList();
            foreach (SYS_CaseCause sYS_CaseCause in sys_caseCausesList)
            {
                if (!string.IsNullOrEmpty(sYS_CaseCause.KeyWords))
                {
                    sys_cause = GetArgumentValueByMatchWords(Convert.ToString(sYS_CaseCause.KeyWords), textcentent);
                }
                if (string.IsNullOrWhiteSpace(sys_cause))
                {
                    bool Ismatch = System.Text.RegularExpressions.Regex.IsMatch(textcentent, "^.*?" + sYS_CaseCause.CC_Name + "|[一案]$");
                    if (Ismatch)
                    {
                        causeList.Add(Convert.ToString(sYS_CaseCause.AllParentId), Convert.ToString(sYS_CaseCause.CC_ID));
                    }
                }
            }
            if (string.IsNullOrWhiteSpace(sys_cause))
            {
                string causecodet = string.Empty;
                foreach (var value in causeList)
                {
                    if (value.Key.Contains(causecodet) || string.IsNullOrWhiteSpace(causecodet))
                    {
                        causecodet = value.Key;
                        sys_cause = value.Value;
                    }
                }
            }

            return sys_cause;
        }

        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        public static string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                //string paternStr = RegexParseClass.GetRegexLastStr("DictMatchingA1");
                string paternStr = @"(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、]){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }

        /// <summary>
        /// 通过案由名称查询情节数据
        /// </summary>
        /// <param name="ccName">案由名称</param>
        /// <param name="isML">是否机器学习</param>
        /// <returns></returns>
        public SYS_CaseCause GetPlotCauseByCCName(string ccName, bool isML)
        {
            var query = freeSql.Select<SYS_CaseCause>()
                             .Where(x => x.CC_Name == ccName)
                             .Where(x => x.CC_NodeType == 5 || x.CC_NodeType == 6)
                             .WhereIf(!isML, x => x.IsML == 0 || x.IsML == null)
                             .WhereIf(isML, x => x.IsML == 1)
                             .ToOne();
            return query;
        }
        #endregion

        #region 获取配置信息
        /// <summary>
        /// 得到System数据表中，相关的行数据。
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="fkField">外键字段</param>
        /// <param name="fkValue">外键值</param>
        /// <returns>DataTable</returns>
        //public DataTable GetTable_System(string TableName, string fkField, string fkValue)
        //{
        //    string strsql = "select * from " + TableName + " Where " + fkField + " ='" + fkValue + "'";

        //    IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strsql.ToString());

        //    return sqhandle.GetSqlHelper.ExecuteReader(dbCommand);
        //}
        #endregion

        /// <summary>
        /// 获取对应的
        /// </summary>
        /// <param name="causeid"></param>
        /// <param name="Sourcename"></param>
        /// <param name="ParagraphCode"></param>
        /// <returns></returns>
        //public DataTable GetArgumentTabel(string causeid, string Sourcename, string ParagraphCode)
        //{
        //    string strsql = @"SELECT
        //                                     b.CC_Name,
        //                                     [ES_ID],
        //                                     b.[CC_ID],
        //                                     [Source_ID],
        //                                     [Source_ParagraphID],
        //                                     [Source_Name],
        //                                     [Source_ParagraphName],
        //                                     t.[CC_RegexInfoCode],
        //                                     [IsParagraphExtract],
        //                                     [IsEvidenceMatch]
        //                                    FROM
        //                                     Ldt_JudgeDocSystem.dbo.[SYS_Express_Source] t
        //                                    LEFT JOIN Ldt_JudgeDocSystem.dbo.SYS_CaseCause b ON t.CC_ID = b.CC_ID
        //                                    WHERE 
        //                                        b.CC_NodeType=16 AND
        //                                     t.Source_ID = '" + Sourcename + "' AND t.Source_ParagraphID = '" + ParagraphCode + "' AND b.AllParentId LIKE '%," + causeid + ",%'";

        //    IDbCommand dbCommand = sqhandle.GetSqlHelper.GetCommand(strsql.ToString());
        //    return sqhandle.GetSqlHelper.ExecuteReader(dbCommand);

        //    var list = freeSql.Select<SYS_Express_Source, SYS_CaseCause>().LeftJoin<SYS_CaseCause>((a, b) => a.CC_ID == b.CC_ID).Where((a, b) => a.Source_ID == Sourcename && b.CC_NodeType == 16).ToList((a, b) => new { a, b });

        //}
    }
}
